import localStorage from '../utils/localStorage';

// 是否需要重置数据
const shoudReset = (localList, newList) => {
  if (!localList) {
    // 本地没有存储过
    return true;
  }
  if (localList && localList.length !== newList.length) {
    // 新增或者删除了元素
    return true;
  }
  // 精确比较
  const preListMap = {}; //
  localList.forEach((i) => {
    // 保存一份以3个为key的 map 保证最大的正确率
    preListMap[`${i.label}${i.value}${i.inputType}`] = i;
  });
  for (let i = 0; i < newList.length; i += 1) {
    if (
      !preListMap[
        `${newList[i].label}${newList[i].value}${newList[i].inputType}`
      ]
    ) {
      return true; // 只要找不到,立马return
    }
  }
  return false;
};
export const getId = () => {
  return `setFilter${localStorage.getItem(
    'userId',
  )}${window.location.pathname.replace(/\//g, '-')}`;
};
export const getList = (preList = []) => {
  let list =
    localStorage.getItem(getId()) && JSON.parse(localStorage.getItem(getId()));
  const preListMap = {}; //
  preList.forEach((i) => {
    // 保存一份以3个为key的 map 保证最大的正确率
    preListMap[`${i.label}${i.value}${i.inputType}`] = i;
  });
  if (shoudReset(list, preList)) {
    list = preList.map((i) => {
      const it = i;
      it.show = true; // 全部显示
      return it;
    });
    // 存
    localStorage.setItem(
      getId(),
      JSON.stringify(
        list.map((i) => {
          const it = { ...i };
          // 删除react元素
          delete it.render;
          delete it.labelRender;
          delete it.listArr; // 该数据太大，不应该存在本地
          return it;
        }),
      ),
    );
    return list;
  } else {
    // 为每一项添加 render方法
    list = list.map((i) => {
      const it = i;
      // it.render = preListMap[it.label].render;
      return {
        ...preListMap[`${i.label}${i.value}${i.inputType}`],
        show: it.show,
      }; // 这样做，本地存储生效的只有，顺序和显示隐藏
    });
    return list;
  }
};
